﻿/**
 * Copyright (c) 2013 Jeremy Wyman
 * Microsoft Public License (Ms-PL)
 * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
 * 1. Definitions
 *    The terms "reproduce", "reproduction", "derivative works", and "distribution" have the same meaning here as under U.S. copyright law.
 *    A "contribution" is the original software, or any additions or changes to the software.
 *    A "contributor" is any person that distributes its contribution under this license.
 *    "Licensed patents" are a contributor's patent claims that read directly on its contribution.
 * 2. Grant of Rights
 *    (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
 *    (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
 * 3. Conditions and Limitations
 *    (A) No Trademark License - This license does not grant you rights to use any contributors' name, logo, or trademarks.
 *    (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
 *    (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
 *    (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
 *    (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 *    
 * More info on: http://tempest.codeplex.com
**/

using System;

namespace Tempest.Hashing
{
    /// <summary>
    /// CRC-64-ECMA-182 standard. 
    /// </summary>
    /// <remarks>
    /// Reference: http://en.wikipedia.org/wiki/Crc64
    /// </remarks>
    internal unsafe class Crc64
    {
        #region Constants
        public enum Polynomial : ulong
        {
            Normal = 0x42F0E1EBA9EA3693,
            Reversed = 0xC96C5795D7870F42,
            ReversedReciprocal = 0xA17870F5D4F51B49,
            Default = Reversed,
        }
        #endregion
        #region Members
        private readonly ulong[] _table;
        #region Static Members
        public static Crc64 Normal
        {
            get
            {
                if (_normal == null)
                    _normal = new Crc64(Polynomial.Normal);
                return _normal;
            }
        }
        public static Crc64 Reversed
        {
            get
            {
                if (_normal == null)
                    _normal = new Crc64(Polynomial.Reversed);
                return _normal;
            }
        }
        public static Crc64 ReversedReciprocal
        {
            get
            {
                if (_normal == null)
                    _normal = new Crc64(Polynomial.ReversedReciprocal);
                return _normal;
            }
        }

        public static Crc64 _normal = null;
        public static Crc64 _reversed = null;
        public static Crc64 _reversedRecpierocal = null;
        #endregion
        #endregion
        #region Constructors
        public Crc64(Polynomial polynomial)
        {
            _table = new ulong[0xFF + 1];
            for (uint i = 0; i < 0xFF; i++)
            {
                ulong e = 0;
                for (int j = 0; j < 8; j++)
                {
                    e = (e >> 1) ^ (((e ^ (i >> j)) & 1) != 0 ? (ulong)polynomial : 0);
                }
                _table[i] = e;
            }
        }
        #endregion
        #region Methods
        /// <summary>
        /// Initialized the hash value for a proper hash
        /// </summary>
        /// <param name="hash">The crc/hash value</param>
        public void Initialize(out ulong hash)
        {
            hash = 0;// ISO3309 initial seed is 0
        }
        /// <summary>
        /// Finalizes the hash value for a final hash
        /// </summary>
        /// <param name="hash">The crc/hash value</param>
        [System.Diagnostics.Conditional("DEBUG")]
        public void Finalize(ref ulong hash)
        {
            // ISO3309 requires no finalization            
        }

        public void Add(ref ulong hash, byte* p, int offset, int count)
        {
            Debug.Assert(p != null || (p == null && count == 0 && offset == 0), "byte pointer cannot be null");
            Debug.Assert(offset >= 0, "offset must be greater than or equal to zero");
            Debug.Assert(count >= 0, "count must be greater than or equal to zero");
            ulong crc = hash;
            for (int i = offset; i < count; i++)
            {
                unchecked
                {
                    crc = (crc >> 8) ^ _table[(crc ^ p[i]) & 0xFF];
                }
            }
            hash = crc;
        }

        public void Add(ref ulong hash, byte value)
        {
            unchecked
            {
                hash = (hash >> 8) ^ _table[value ^ hash];
            }
        }

        public void Add(ref ulong hash, int value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(int));
        }

        public void Add(ref ulong hash, uint value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(uint));
        }

        public void Add(ref ulong hash, long value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(long));
        }

        public void Add(ref ulong hash, ulong value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(ulong));
        }

        public void Add(ref ulong hash, string value)
        {
            char[] chars = value.ToCharArray();
            fixed (char* p = chars)
            {
                Add(ref hash, (byte*)p, 0, sizeof(char) * chars.Length);
            }
        }

        public void Add(ref ulong hash, double value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(double));
        }

        public void Add(ref ulong hash, float value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(float));
        }

        public void Add(ref ulong hash, bool value)
        {
            Add(ref hash, (byte)(value ? 1 : 0));
        }

        public void Add(ref ulong hash, string value, System.Text.Encoding encoding)
        {
            byte[] bytes = encoding.GetBytes(value);
            fixed (byte* p = bytes)
            {
                Add(ref hash, p, 0, bytes.Length);
            }
        }

        public void Add(ref ulong hash, DateTime value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(DateTime));
        }

        public void Add(ref ulong hash, Guid value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(Guid));
        }

        public void Add(ref ulong hash, TimeSpan value)
        {
            byte* p = (byte*)&value;
            Add(ref hash, p, 0, sizeof(TimeSpan));
        }

        public void Add(ref ulong hash, byte[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (byte* p = buffer)
            {
                Add(ref hash, p, offset, count);
            }
        }

        public void Add(ref ulong hash, char[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (char* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(char) * count);
            }
        }

        public void Add(ref ulong hash, short[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (short* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(short) * count);
            }
        }

        public void Add(ref ulong hash, ushort[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (ushort* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(ushort) * count);
            }
        }

        public void Add(ref ulong hash, int[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (int* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(int) * count);
            }
        }

        public void Add(ref ulong hash, uint[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (uint* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(uint) * count);
            }
        }

        public void Add(ref ulong hash, long[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (long* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(long) * count);
            }
        }

        public void Add(ref ulong hash, ulong[] buffer, int offset, int count)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            Debug.Assert(offset >= 0 || offset < buffer.Length, "the offset is outside the bounds of the array");
            Debug.Assert(count >= 0 || count < buffer.Length, "the count is outside the bounds of the array");
            Debug.Assert(buffer.Length >= offset + count, "offset + count cannot exceed the length");
            fixed (ulong* p = buffer)
            {
                Add(ref hash, (byte*)p, offset, sizeof(ulong) * count);
            }
        }

        public void Add(ref ulong hash, byte[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (byte* p = buffer)
            {
                Add(ref hash, p, 0, buffer.Length);
            }
        }

        public void Add(ref ulong hash, char[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (char* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(char) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, short[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (short* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(short) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, ushort[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (ushort* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(ushort) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, int[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (int* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(int) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, uint[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (uint* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(uint) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, long[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (long* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(long) * buffer.Length);
            }
        }

        public void Add(ref ulong hash, ulong[] buffer)
        {
            Debug.Assert(buffer != null, "the buffer cannot be null");
            fixed (ulong* p = buffer)
            {
                Add(ref hash, (byte*)p, 0, sizeof(ulong) * buffer.Length);
            }
        }

        public void Reverse(ref ulong value)
        {
            ulong r = 0;
            for (int i = 0; i < 64; ++i)
            {
                unchecked
                {
                    if ((value & 1) != 0)
                    {
                        r |= (0x8000000000000000 >> i);
                    }
                    value >>= 1;
                }
            }
            value = r;
        }
        #endregion
    }
}
